<template>
  <div class="tool-container">
    <el-button
      v-if="!readonly && allowSave"
      type="primary"
      :loading="btnLoading"
      @click="handleSaveForm"
    >保存</el-button>
    <el-button
      v-if="!readonly && allowSubmit"
      type="primary"
      :loading="btnLoading"
      @click="handleSubmitForm"
    >提交</el-button>
    <el-button
      v-for="(item, index) in cmdList"
      :key="index"
      :type="getBtnType(item)"
      :loading="btnLoading"
      @click="handleBtnClick(item)"
    >
      {{ item.cmd_des }}
    </el-button>
    <el-button
      @click="backList"
    >
      返回
    </el-button>
    <user-select :outerTag="outerTag" :multi="false" :user2Local="user2Local" :dialog-visible.sync="dialogVisible" @confirm="handleConfirm" />
    <common-dialog
      :dialog-visible.sync="cmdVisible"
      :title="cmdTitle"
      width="800px"
      @confirm="handleCmdConfirm"
    >
      <el-form ref="cmdform" :model="cmdForm" :rules="rules" label-width="100px">
        <el-form-item v-if="isTransfer" label="转办人:" prop="personId">
          <el-select v-model="cmdForm.personId" style="width:250px;" placeholder="请选择" @focus="dialogVisible=true">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="cmdVisible" label="意见留言:" prop="cmdMemo">
          <el-input
            ref="cmdMemo"
            v-model="cmdForm.cmdMemo"
            type="textarea"
            autofocus
            show-word-limit
            :maxlength="200"
            :rows="2"
            placeholder="请输入意见留言"
          />
        </el-form-item>
      </el-form>
    </common-dialog>
  </div>
</template>
<script>
import {
  invokeMethod
} from '@/api/common'
import {
  runTask,
  saveWf
} from '@/api/workflow'
import UserSelect from '@admin/components/userSelect/index'
import {
  getUrlParam2,
  windowClose
} from '@/utils/index'
export default {
  name: 'ApproveCmd',
  components: {
    UserSelect
  },
  props: {
    todoInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    commonSave: {
      type: Function,
      required: true
    },
    commonValidate: {
      type: Function,
      required: true
    }
  },
  data() {
    return {
      cmdList: [],
      btnLoading: false,
      dialogVisible: false,
      cmdId: '',
      cmdVisible: false,
      cmdTitle: '',
      cmdForm: {
        personId: '',
        personName: '',
        cmdMemo: ''
      },
      btnInfo: {},
      outerTag: window.g?.userSelect?.outerTag || '0',
      user2Local: window.g?.userSelect?.user2Local || '0',
    }
  },
  computed: {
    oInsId: function() {
      return this.$route.query.parentDataId
    },
    readonly: function() {
      return this.todoInfo.readonly
    },
    allowSave: function() {
      return this.todoInfo.allowSave
    },
    allowSubmit: function() {
      return this.todoInfo.allowSubmit
    },
    navCode: function() {
      return this.customPage?.navCode || ''
    },
    options: function() {
      if (this.cmdForm.personId) {
        return [{
          label: this.cmdForm.personName,
          value: this.cmdForm.personId
        }]
      } else {
        return []
      }
    },
    rules: function() {
      return {
        personId: [{ required: true, message: '请选择转办人', trigger: 'blur' }],
        cmdMemo: [{ required: this.btnInfo.require_process_memo == 1, message: '请输入意见留言', trigger: 'blur' }]
      }
    },
    // 转办
    isTransfer() {
      return this.btnInfo.cmd_type === '5'
    },
    // 退回
    isBack() {
      return this.btnInfo.cmd_type === '4'
    }
  },
  watch: {
    cmdVisible: function(visible) {
      if (visible) {
        setTimeout(() => {
          this.$refs.cmdMemo.focus()
        })
      } else {
        const oriForm = this.$options.data().cmdForm
        Object.keys(oriForm).forEach(key => {
          this.cmdForm[key] = oriForm[key]
        })
      }
    }
  },
  mounted: function() {
    this.cmdList = this.todoInfo.cmdList.sort((pre, next) => {
      return pre.order_id > next.order_id ? 1 : -1
    })
    this.cmdForm.cmdMemo = this.todoInfo.processMemo || ''
  },
  methods: {
    // 按钮类型
    getBtnType({ cmd_type }) {
      switch (cmd_type) {
        // 驳回
        case '3':
          return 'danger'
        default:
          return 'primary'
      }
    },
    // 返回列表页
    backList() {
      if (getUrlParam2('_layout') === '0,0') {
        windowClose()
        return
      }
      const view = this.$route
      this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
        this.$router.back()
      })
    },
    // 保存
    handleSaveForm() {
      this.$emit('save')
    },
    // 提交
    handleSubmitForm() {
      this.$emit('submit')
    },
    // 转办
    handleConfirm(users) {
      const user = users[0]
      this.cmdForm.personId = user.user_code
      this.cmdForm.personName = user.user_name + '(' + user.user_code + ')'
      this.dialogVisible = false
    },
    customCommonSave() {
      // 转办和退回不保存表单
      if (this.isTransfer || this.isBack) {
        return Promise.resolve()
      } else {
        return this.commonSave()
      }
    },
    handleCmdConfirm() {
      this.$refs.cmdform.validate(valid => {
        if (valid) {
          this.customCommonSave().then(() => {
            const params = {
              cmdId: this.cmdId,
              oInsId: this.oInsId,
              cmdMemo: this.cmdForm.cmdMemo || '',
              designationUser: this.cmdForm.personId
            }
            this.btnLoading = true
            runTask(params).then((res) => {
              if (res.success) {
                this.$$success(res.message)
                setTimeout(() => {
                  this.backList()
                }, 500)
              } else {
                this.$$message(res.message)
              }
            }).finally(() => {
              this.btnLoading = false
            })
          })
        }
      })
    },
    // 按钮点击
    handleBtnClick(btn) {
      const { id, cmd_des } = btn
      this.btnInfo = btn
      this.cmdId = id
      this.cmdTitle = cmd_des
      if (this.isTransfer || this.isBack) {
        this.cmdVisible = true
      } else {
        this.commonValidate().then(() => {
          this.cmdVisible = true
        }).catch((e) => {
          this.$$message('请检查表单')
        })
      }
    }
  }
}
</script>
<style lang='scss' scoped>
</style>
